import { login, logout, getInfo, register, getadminsInfo, deleteadminInfo, putadminInfo, postadminsInfo, getidadminInfo } from '@/api/admin'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import axios from 'axios'


const getDefaultState = () => {
    return {
        token: getToken(),
        name: getToken(),
        avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        adminInfoStatus: {},
        adminId: ""
    }
}

const state = getDefaultState()
const getters = {
    getAdminInfoStatus(state) {
        return state.adminInfoStatus;
    },
    getAdminId(state) {
        return state.adminId;
    }
}
const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    getAdminStatusMutations: (state, payload) => {
        state.adminInfo = payload;
    },
    getAdminIdMutations: (state, payload) => {
        state.adminId = payload;
    }
}

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { account, password } = userInfo
        return new Promise((resolve, reject) => {
            login({ account: account.trim(), password: password }).then(response => {
                // 获取到当前输入用户的角色（平台管理员：0，门店管理员：1）
                commit('SET_TOKEN', response.data[0].position);
                localStorage.setItem("roleInfo", response.data[0].position);
                // 将 token 存到本地
                localStorage.setItem("admin_token", response.token)
                // 如果是平台管理员就直接进入
                if (response.data[0].position == 0) {
                    resolve(response.data[0])
                }
                // 门店管理员就将门店管理员的id存到仓库后进入
                else {
                    // commit('getAdminIdMutations', response.data[0]._id);
                    localStorage.setItem('adminId', response.data[0]._id)
                    resolve(response.data[0])
                }
            }).catch(error => {
                reject(error)
            })
        })
    },

    // get user info
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo(state.token).then(response => {
                const { data } = response
                if (!data) {
                    return reject('Verification failed, please Login again.')
                }
                const { name, avatar } = data
                commit('SET_NAME', name)
                commit('SET_AVATAR', avatar)
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            logout(state.token).then(() => {
                removeToken() // must remove  token  first
                resetRouter()
                commit('RESET_STATE')
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken() // must remove  token  first
            commit('RESET_STATE')
            resolve()
        })
    },

    // 注册
    register({ commit }, adminInfo) {
        return new Promise((resolve, reject) => {
            register(adminInfo).then(() => {
                resolve();
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 用户管理
    // 获取所有管理员
    getadminsInfo({ commit }, payload) {
        return new Promise((resolve, reject) => {
            getadminsInfo().then((res) => {
                resolve(res)
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 新增平台管理员
    postadminInfo({ commit }, adminInfo) {
        return new Promise((resolve, reject) => {
            postadminsInfo(adminInfo).then(() => {
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    deleteadminInfo({ commit }, id) {
        return new Promise((resolve, reject) => {
            deleteadminInfo(id).then(() => {
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 修改管理员
    putadminInfo({ commit }, item) {
        return new Promise((resolve, reject) => {
            putadminInfo(item).then(() => {
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 根据id查询管理员
    getidadminInfo({ commit }, id) {
        return new Promise((resolve, reject) => {
            getidadminInfo(id).then((res) => {
                resolve(res)
            }).catch(error => {
                reject(error)
            })
        })
    },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}

